package com.springboot.practice.repository;

import com.springboot.practice.domain.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author 小柯
 * @Date 2019/9/22  9:30
 *
 * 目前存储在内存当中，map
 *
 **/

@Repository
public class UserRepositoryImpl implements UserRepository {

    private static AtomicLong counter = new AtomicLong(); //每次递增+1
    private final ConcurrentMap<Long, User> userConcurrentMap = new ConcurrentHashMap<>();

    @Override
    public User saveOrUpdateUaser(User user) {
        Long id = user.getId();
        if(id == null){
            id = counter.incrementAndGet();
            user.setId(id);
        }
        this.userConcurrentMap.put(id,user);
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        userConcurrentMap.remove(id);
    }

    @Override
    public User getUserById(Long id) {
        return userConcurrentMap.get(id);
    }

    @Override
    public List<User> listUser() {
        return new ArrayList<User>(this.userConcurrentMap.values());
    }
}
